#include "net_pre.h"
#include "acceptor.h"

namespace Net
{
	Acceptor::Acceptor(boost::asio::io_service& io_service, ushort listen_port)
		: io_service_(io_service), listen_port_(listen_port),
		acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), listen_port), true )
	{
		
	}

	Acceptor::~Acceptor()
	{

	}

	void Acceptor::Start()
	{
		Listen();
	}

	void Acceptor::Listen()
	{
		INetSessionPtr new_session(new INetSession(io_service_));
		acceptor_.async_accept(new_session->GetSocket(), boost::bind(&Acceptor::ListenHandle, this, boost::asio::placeholders::error, new_session));
	}

	void Acceptor::ListenHandle(boost::system::error_code ec, INetSessionPtr net_session)
	{
		if (!ec)
		{
			boost::mutex::scoped_lock lock(mutex_);
			accept_sessions_.push(net_session);
		}

		Listen();
	}
}